<template>
  <div class="container_search">
    <el-input
        v-model="username"
        style="width: 240px"
        placeholder="用户名"
        clearable
    />
    <el-input
        v-model="account"
        style="width: 240px"
        placeholder="账号"
        clearable
    />
    <el-radio-group v-model="role" @change="getUserData">
      <el-radio label="">全部</el-radio>
      <el-radio label="admin">管理员</el-radio>
      <el-radio label="teacher">老师</el-radio>
      <el-radio label="student">学生</el-radio>
    </el-radio-group>
    <el-radio-group v-model="statu" @change="getUserData">
      <el-radio-button label="活跃" value="0" />
      <el-radio-button label="冻结" value="1" />
    </el-radio-group>
    <div class="c_button">
      <el-button type="primary" style="width: 20%" @click="getUserData">搜索</el-button>
      <el-button type="success" style="width: 20%" @click="updateData" :disabled="isUpdate" v-if="statu==0">修改</el-button>
      <el-button type="danger" style="width: 20%" @click="deleteData" :disabled="isDelete" v-if="statu==0">冻结</el-button>
      <el-button type="success" style="width: 20%"@click="resetData" :disabled="isDelete" v-else>解冻</el-button>
      <el-button type="seacher" :icon="Plus" circle @click="addData" :disabled="!isUpdate"/>
    </div>
  </div>
<div>
  <el-table :data="userData" style="width: 100%" @selection-change="handleSelectionChange">
    <el-table-column label="序号" width="80" align="center">
      <template #default="scope">
        {{ (currentPage - 1) * pagesize + scope.$index + 1 }}
      </template>
    </el-table-column>
    <el-table-column type="selection" width="55"align="center"header-align="center"/>
    <el-table-column property="username" label="姓名"align="center"header-align="center" />
    <el-table-column property="account" label="账号" align="center"header-align="center"/>
    <el-table-column property="role" label="角色" align="center"header-align="center"/>
    <el-table-column property="createdAt" label="创建时间" align="center"header-align="center" :formatter="formatDate"/>
    <el-table-column property="email" label="邮箱" align="center"header-align="center"/>
    <el-table-column property="avatar" label="头像" align="center"header-align="center">
      <template #default="{row}">
        <img :src="row.avatar?row.avatar:'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" alt=""
             style="width: 40px; height: 40px; border-radius: 50%"
              @error="handleImageError"
        >
      </template>
    </el-table-column>
  </el-table>
</div>
  <div class="pagination">
    <el-pagination
        v-model:current-page="pageno"
        v-model:page-size="pagesize"
        :page-sizes="[10, 20, 40, 80]"
        :size="size"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
  <el-dialog
      v-model="dialogVisible"
      :title="diaTitle"
      width="500"
      :before-close="handleClose"
  >
    <el-form :model="userinfo" label-width="auto" style="max-width: 600px" :rules="rules" ref="ruleFromRef">
      <el-form-item label="用户名">
        <el-input v-model="userinfo.username" clearable/>
      </el-form-item>
      <el-form-item label="账号">
        <el-input v-model="userinfo.account" clearable/>
      </el-form-item>
      <el-form-item label="密码">
        <el-input type="password" v-model="userinfo.password" clearable/>
      </el-form-item>
      <el-form-item label="角色">
        <el-radio-group v-model="userinfo.role">
          <el-radio label="admin">管理员</el-radio>
          <el-radio label="teacher">老师</el-radio>
          <el-radio label="student">学生</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="userinfo.email" clearable/>
      </el-form-item>
      <el-form-item label="头像">
        <el-input v-model="userinfo.avatar" clearable/>
        <img :src="userinfo.avatar?userinfo.avatar:'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" style="width: 55px" v-if="!isAdd">
      </el-form-item>
      <el-form-item style="justify-content: center">
        <el-button type="primary" @click="confirm(ruleFromRef)">确定</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

</template>
<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import {Search, Add, Update, Delete, ResetData} from '../../../api/user.js'
import {ElMessage} from "element-plus";
import {Plus} from "@element-plus/icons-vue/global";
import dayjs from "dayjs";

const statu=ref('0')
const currentPage=ref(1)
const pageno=ref(1)
const pagesize=ref(10)
const userData=ref([{
  userId: 1,
  account: "admin",
  username: "admin",
  role: "admin",
  createdAt: "2023-10-01", // 确保有 date 字段
  email: "xxx" ,     // 确保有 address 字段
  avatar:""
}])
const username=ref('')
const account=ref('')
const role=ref('')
const total=ref(0)
const size = ref('default')
const background = ref(false)
const disabled = ref(false)
const isUpdate = ref(true)
const isDelete = ref(true)
const isAdd = ref(true)
const diaTitle=ref()
const userinfo=ref({
  userId: 1,
  account: "admin",
  username: "admin",
  password: "admin",
  role: "admin",
  email: "xxx" ,     // 确保有 address 字段
  avatar:""
})
const userinfolist=ref([])
const dialogVisible=ref(false)
const getUserData=()=>{
  Search({
    pageno:pageno.value,
    pagesize:pagesize.value,
    username:username.value,
    account:account.value,
    role:role.value,
    status:statu.value
  }).then(res=>{
    userData.value=res.data.data.records
    console.log(userData)
    total.value=res.data.data.total
  })
}
const updateData=()=>{
  diaTitle.value = '修改用户'
  dialogVisible.value = true
  isAdd.value=false
}
const confirm=async (formEl)=>{
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
  if (isAdd.value)
    Add(userinfo.value).then(res=>{
      getUserData()
      ElMessage({
        message:'添加成功',
        type:'success'
      })
    })
  else
    Update(userinfo.value).then(res=>{
      getUserData()
      ElMessage({
        message:'修改成功',
        type:'success'
      })
    })
  dialogVisible.value = false
}
const addData=()=>{
  diaTitle.value = '添加用户'
  userinfo.value={}
  dialogVisible.value = true
  isAdd.value=true
}
const deleteData=()=>{
  for(let item of userinfolist.value){
    if (JSON.parse(localStorage.getItem('userInfo')).userId===item.userId)
      return ElMessage.error('不能删除该用户，权限不够')
  }
  Delete(userinfolist.value).then(res=>{
    ElMessage.success(res.data.message)
    getUserData()
  })
}
const resetData=()=>{
  ResetData(userinfolist.value).then(res=>{
    ElMessage.success(res.data.message)
    getUserData()
  })
}
const handleClose=(done)=>{
  dialogVisible.value = false
  done()
}
const handleSizeChange=(val)=>{
  pagesize.value=val
  getUserData()
}
const handleCurrentChange=(val)=>{
  pageno.value=val
  getUserData()
}
const handleImageError = (e) => {
  e.target.src = 'https://example.com/default-avatar.png'; // 你的默认图地址
}
const handleSelectionChange=(val)=>{
  console.log("选中的数据",val)
  if (val.length===0)
    return isUpdate.value=true,isDelete.value=true
  else if (val.length===1)
    return isUpdate.value=false,isDelete.value=false,userinfo.value=val[0],userinfolist.value=val
  else if (val.length>1)
    return isUpdate.value=true,isDelete.value=false,userinfolist.value=val
}
//用于表单验证的函数
const ruleFromRef=ref()
const validateAccount=(rule,value,callback)=>{
  if(value===''){
    callback(new Error('账号不能为空'))
  }else{
    const uPattern = /^[a-zA-Z0-9_-]{4,16}$/
    uPattern.test(value)?callback():callback(new Error('账号格式不正确'))
  }
}
const validatePassword=(rule,value,callback)=>{
  if(value===''){
    callback(new Error('密码不能为空'))
  }else{
    const uPass = /^[a-zA-Z0-9_-]{4,16}$/
    uPass.test(value)?callback():callback(new Error('密码格式不正确'))
  }
}
const validateUsername=(rule,value,callback)=>{
  if(value===''){
    callback(new Error('用户名不能为空'))
  }else{
    callback()
  }
}
const validateEmail=(rule,value,callback)=>{
  if(value===''){
    callback(new Error('邮箱不能为空'))
  }else{
    //const uEmail = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
    const uEmail = /^([A-Za-z0-9_\-\.]+)@([A-Za-z0-9_\-\.]+)\.([A-Za-z]{2,4})$/
    // 邮箱的正则表达式/^([A-Za-z0-9_\-\.]+)@([A-Za-z0-9_\-\.]+)\.([A-Za-z]{2,4})$/.
    uEmail.test(value)?callback():callback(new Error('邮箱格式不正确'))
  }
}
const validateAvatar=(rule,value,callback)=>{
  if(value===''){
    callback(new Error('头像不能为空'))
  }else{
    const uAvatar = /^((https?|ftp|file):\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/
    uAvatar.test(value)?callback():callback(new Error('头像格式不正确'))
  }
}
const rules=reactive({
  account:[{validator:validateAccount,trigger:'blur'}],
  password:[{validator:validatePassword,trigger:'blur'}],
  username:[{validator:validateUsername,trigger:'blur'}],
  email:[{validator:validateEmail,trigger:'blur'}],
  avatar:[{validator:validateAvatar,trigger:'blur'}],
})
const formatDate=(row, column, cellValue)=> {
  // 使用 dayjs 格式化日期
  return cellValue ? dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss') : '';
}
onMounted(()=>{
  getUserData()
})
</script>
<style lang="less" scoped>
.container_search{
  width: 100%;
  display: flex;
  justify-content: space-between;
  .c_button{
    display: flex;
    width: 40%;
    justify-content: space-between;
  }
}
.pagination{
  width: 100%;
  display: flex;
  margin: 0 auto;
  justify-content: center;
}
</style>
